package com.xujie.property_warranty_system.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xujie.property_warranty_system.dto.MaintenanceDTO;
import com.xujie.property_warranty_system.dto.PageResult;
import com.xujie.property_warranty_system.entity.Facility;
import com.xujie.property_warranty_system.entity.FacilityMaintenance;
import com.xujie.property_warranty_system.enums.FacilityStatus;
import com.xujie.property_warranty_system.enums.MaintenanceResult;
import com.xujie.property_warranty_system.mapper.FacilityMaintenanceMapper;
import com.xujie.property_warranty_system.mapper.FacilityMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 设备维护记录服务类
 */
@Service
public class MaintenanceService extends ServiceImpl<FacilityMaintenanceMapper, FacilityMaintenance> {
    
    @Autowired
    private FacilityMaintenanceMapper maintenanceMapper;
    
    @Autowired
    private FacilityMapper facilityMapper;
    
    /**
     * 分页查询设备维护记录
     */
    public PageResult<FacilityMaintenance> getMaintenancePage(Long facilityId, Integer page, Integer size) {
        // 创建分页对象
        Page<FacilityMaintenance> pageObj = new Page<>(page, size);
        
        // 构建查询条件
        QueryWrapper<FacilityMaintenance> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("facility_id", facilityId);
        queryWrapper.orderByDesc("maintenance_date");
        
        // 执行分页查询
        Page<FacilityMaintenance> maintenancePage = maintenanceMapper.selectPage(pageObj, queryWrapper);
        
        return new PageResult<>(
            maintenancePage.getRecords(),
            maintenancePage.getTotal(),
            (int) maintenancePage.getCurrent(),
            (int) maintenancePage.getSize()
        );
    }
    
    /**
     * 获取设备维护记录详情
     */
    public FacilityMaintenance getMaintenanceDetail(Long id) {
        FacilityMaintenance maintenance = maintenanceMapper.selectById(id);
        if (maintenance == null) {
            throw new RuntimeException("维护记录不存在");
        }
        
        return maintenance;
    }
    
    /**
     * 添加设备维护记录
     */
    @Transactional
    public Long addMaintenance(MaintenanceDTO maintenanceDTO) {
        // 检查设备是否存在
        Facility facility = facilityMapper.selectById(maintenanceDTO.getFacilityId());
        if (facility == null) {
            throw new RuntimeException("设备不存在");
        }
        
        // 创建维护记录对象
        FacilityMaintenance maintenance = new FacilityMaintenance();
        BeanUtils.copyProperties(maintenanceDTO, maintenance);
        
        // 保存维护记录
        maintenanceMapper.insert(maintenance);
        
        // 更新设备信息
        updateFacilityAfterMaintenance(facility, maintenanceDTO);
        
        return maintenance.getId();
    }
    
    /**
     * 更新设备维护记录
     */
    @Transactional
    public void updateMaintenance(MaintenanceDTO maintenanceDTO) {
        if (maintenanceDTO.getId() == null) {
            throw new RuntimeException("维护记录ID不能为空");
        }
        
        // 检查维护记录是否存在
        FacilityMaintenance existingMaintenance = maintenanceMapper.selectById(maintenanceDTO.getId());
        if (existingMaintenance == null) {
            throw new RuntimeException("维护记录不存在");
        }
        
        // 检查设备是否存在
        Facility facility = facilityMapper.selectById(maintenanceDTO.getFacilityId());
        if (facility == null) {
            throw new RuntimeException("设备不存在");
        }
        
        // 更新维护记录
        FacilityMaintenance maintenance = new FacilityMaintenance();
        BeanUtils.copyProperties(maintenanceDTO, maintenance);
        
        maintenanceMapper.updateById(maintenance);
        
        // 更新设备信息
        updateFacilityAfterMaintenance(facility, maintenanceDTO);
    }
    
    /**
     * 删除设备维护记录
     */
    @Transactional
    public void deleteMaintenance(Long id) {
        // 检查维护记录是否存在
        FacilityMaintenance maintenance = maintenanceMapper.selectById(id);
        if (maintenance == null) {
            throw new RuntimeException("维护记录不存在");
        }
        
        // 删除维护记录
        maintenanceMapper.deleteById(id);
    }
    
    /**
     * 获取设备最近的维护记录
     */
    public List<FacilityMaintenance> getRecentMaintenanceRecords(Long facilityId, int limit) {
        QueryWrapper<FacilityMaintenance> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("facility_id", facilityId);
        queryWrapper.orderByDesc("maintenance_date");
        queryWrapper.last("LIMIT " + limit);
        
        return maintenanceMapper.selectList(queryWrapper);
    }
    
    /**
     * 维护后更新设备信息
     */
    private void updateFacilityAfterMaintenance(Facility facility, MaintenanceDTO maintenanceDTO) {
        boolean needUpdate = false;
        
        // 更新设备状态（如果维护结果为建议报废）
        if (maintenanceDTO.getMaintenanceResult() == MaintenanceResult.SCRAP.getCode()) {
            facility.setStatus(FacilityStatus.SCRAPPED.getCode());
            needUpdate = true;
        } 
        // 如果维护结果为正常，则将设备状态设为正常
        else if (maintenanceDTO.getMaintenanceResult() == MaintenanceResult.NORMAL.getCode()) {
            facility.setStatus(FacilityStatus.NORMAL.getCode());
            needUpdate = true;
        }
        
        // 更新最后维护日期
        LocalDate maintenanceDate = maintenanceDTO.getMaintenanceDate().toLocalDate();
        facility.setLastMaintenanceDate(maintenanceDate);
        
        // 计算下次维护日期
        if (facility.getMaintenanceCycle() != null) {
            facility.setNextMaintenanceDate(maintenanceDate.plusDays(facility.getMaintenanceCycle()));
        }
        
        needUpdate = true;
        
        if (needUpdate) {
            facilityMapper.updateById(facility);
        }
    }
}
